package com.wing.cms.controller;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wing.cms.domain.Channel;
import com.wing.cms.domain.Lookfeel;
import com.wing.cms.service.ChannelManager;
import com.wing.cms.service.LayoutManager;
import com.wing.cms.service.LookfeelManager;
import com.wing.common.Constants;
import com.wing.common.util.ApplicationPath;
import com.wing.common.util.PageBean;
import com.wing.common.util.RequestUtils;

/**
 * 
 * 
 * @author please write your big name
 * 
 */

@Controller
@RequestMapping(value = "/cms/channel")
public class ChannelController {

	@Autowired
	private ChannelManager channelManager;
	@Autowired
	private LayoutManager layoutManager;
	@Autowired
	private LookfeelManager lookfeelManager;

	/**
	 * 获得列表数据
	 * 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "/cms/channel/channelIndex";
	}

	@RequestMapping(value = "get/{url}", method = RequestMethod.GET)
	public String delete(@PathVariable
	String url) {
		return "/cms/channel/" + url;
	}

	@RequestMapping(value = "list", method = RequestMethod.POST)
	public @ResponseBody
	PageBean list(int currentPage, String pageSize, String pid,
			HttpServletRequest request) {
		String siteId = (String) request.getSession().getAttribute(
				Constants.SESSION_SITE_ID);
		int _iPageSize = 0;
		if (pageSize == null) {
			_iPageSize = PageBean.DEFAULT_PAGESIZE;
		} else {
			_iPageSize = Integer.parseInt(pageSize);
		}
		if (pid == null || "null".equals(pid)) {
			pid = Channel.CHANNELROOT;
		}
		return channelManager
				.findPageList(currentPage, _iPageSize, siteId, pid);
	}

	/**
	 * 打开编辑页面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toForm/{id}", method = RequestMethod.GET)
	public String toEditPage(@PathVariable
	String id, String pid, Model model, HttpServletRequest request) {
		String siteId = (String) request.getSession().getAttribute(
				Constants.SESSION_SITE_ID);
		Channel channel = null;
		if (!id.equals("0")) {
			channel = channelManager.findById(id);
		} else {
			channel = new Channel();
			if("null".equals(pid) || pid==null){
				pid=Channel.CHANNELROOT;
			}
			channel.setPid(pid);
			channel.setOrder_num(100);
		}
		List layouts = layoutManager.findAll(siteId);
		List lfs = lookfeelManager.findAll(siteId);
		model.addAttribute("layouts", layouts);
		model.addAttribute("lfs", lfs);
		model.addAttribute("channel", channel);
		return "/cms/channel/channelForm";
	}

	@RequestMapping(value = "save", method = RequestMethod.POST)
	public @ResponseBody
	String save(Channel channel, HttpServletRequest request) {
		String siteId = (String) request.getSession().getAttribute(
				Constants.SESSION_SITE_ID);
		channel.setSite_id(siteId);
//		System.out.println("++++++++++++++++++++"+siteId+"++++++++");
		channelManager.saveChannel(channel);
		return Constants.DEFAULT_AJAX_SUCCESS;
	}

	@RequestMapping(value = "delchannels", method = RequestMethod.POST)
	public @ResponseBody
	String delchannels(String[] chk) throws IOException {
		channelManager.deleteChannels(chk);
		return "" + chk.length;
	}
	
	//复制频道
	@RequestMapping(value = "clone/{id}")
	public @ResponseBody String clone(@PathVariable	String id) throws ServletException, IOException {
		channelManager.cloneChannel(id);
		return Constants.DEFAULT_AJAX_SUCCESS;	

	}

	/**
	 * 是根据频道parentId获取的频道,生成树
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 * 
	 * @throws ServletException,
	 *             IOException
	 */
	@RequestMapping(value = "showTree", method = RequestMethod.GET)
	public void showTree(HttpServletRequest request,
			HttpServletResponse response) {
		String siteId = (String) request.getSession().getAttribute(
				Constants.SESSION_SITE_ID);
		response.setContentType("text/xml;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");// HTTP 1.1
		response.setHeader("Cache-Control", "no-cache");// HTTP 1.0
		response.setHeader("Expires", "0");// 防止被proxy

		String pid = request.getParameter("id");
		boolean firstFlag = false;
		if (pid == null || pid.equalsIgnoreCase("")) {
			pid = Channel.CHANNELROOT;// 我数据库中一级节点的parentid都是-1
			firstFlag = true;
		}
		try {
			// 根据上一级节点,查询该节点下的所有节点
			// String aa = codeManager.createDHTMLXML(pid,firstFlag,domainId);
			response.getWriter().write(
					channelManager.createDHTMLXML(pid, firstFlag, siteId));
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "layout/{id}")
	public @ResponseBody String layout(@PathVariable
	String id,HttpServletRequest request,String s,String cd,
	HttpServletResponse response,Model model) throws ServletException, IOException {
		
		request.setAttribute("channelId", id);
		request.setAttribute("s", s);
		if(cd==null){
			cd="";
		}
		request.setAttribute("cd", cd);
		String sitePath = RequestUtils.getSitePath(request);
		String lookfeel= "default";
		request.setAttribute("lookfeel", lookfeel);
		if(id.indexOf("a,")!= -1){
			String arcticlePathFlag = "aaaaaaaaaaaaaaaaaaaaaa";
			int size = arcticlePathFlag.length();
			for(int i = 0; i < size; i++){
				if(id.indexOf(arcticlePathFlag+",")!= -1){
					String path = id.substring(0,id.indexOf(arcticlePathFlag+","));
					if(path == null||path.equals("")){
						request.getRequestDispatcher("/site/"+sitePath+"/framework/layout/article.jsp").forward(request, response);
					}else{
						request.getRequestDispatcher("/site/"+sitePath+"/framework/layout/article"+path+".jsp").forward(request, response);
					}
					break;
				}
				arcticlePathFlag = arcticlePathFlag.substring(0,arcticlePathFlag.length() -1);
			}
			return null;
		}else if(id.indexOf("p,")!= -1){
			String productPathFlag = "ppppppppppppppppppppppp";
			int size = productPathFlag.length();
			for(int i = 0; i < size; i++){
				if(id.indexOf(productPathFlag)!= -1){
					String path = id.substring(0,id.indexOf(productPathFlag+","));
					if(path == null||path.equals("")){
						request.getRequestDispatcher("/site/"+sitePath+"/framework/layout/product.jsp").forward(request, response);
					}else{
						request.getRequestDispatcher("/site/"+sitePath+"/framework/layout/product"+path+".jsp").forward(request, response);
					}
					break;
				}
				productPathFlag = productPathFlag.substring(0,productPathFlag.length() -1);
			}
			return null;
		}else{
			Channel c = channelManager.findById(id);
			if(c.getLookandfeel()!=null){
				Lookfeel look = lookfeelManager.findById(c.getLookandfeel());
				lookfeel = look.getFilename();
			}
		}
		request.setAttribute("lookfeel", lookfeel);
		request.getRequestDispatcher("/site/"+channelManager.findSitePathById(id)+"/framework/layout/"+channelManager.findLayoutFileById(id)+".jsp").forward(request, response);
		
		System.out.println("+++++++++++++++++channel layout:"+(new Date().getTime())+"++++++++++++++++++++++++++++");
		return null;
	}

	@RequestMapping(value = "pub/{id}", method = RequestMethod.POST)
	public  @ResponseBody String pub(@PathVariable String id,HttpServletRequest request) {
		  String sitePath = RequestUtils.getSitePath(request);
	      URL u;
	      InputStream is = null;
	      DataInputStream dis;
	      String s;
	      URLConnection conn = null;
			File file = new File(ApplicationPath.getParameter("appRoot")+"/site/"+sitePath+"/"+id+".html");
			if(file.exists()){
				file.delete();
			}
			BufferedWriter bw=null;
	      try {
	    	 String urlStr="http://"+request.getServerName()+":"+request.getLocalPort()+"/"+request.getContextPath()+"/cms/channel/layout/"+id+"?ispub=1";
	    	 
	    	 
	         u = new URL(urlStr);
	         conn = u.openConnection();
	         conn.setConnectTimeout(5000);
	         is = conn.getInputStream();
	         dis = new DataInputStream(new BufferedInputStream(is));
	         file.createNewFile();
			 Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); 

	         while ((s = dis.readLine()) != null) {
	        	 s = new String(s.getBytes("ISO8859_1"),"UTF-8");
	        	 writer.write(s);
	        	 writer.write("\r\n");
	         }
	         writer.flush();
	      } catch (MalformedURLException mue) {
	         System.out.println("出错了! 此URL格式不正确.");
	         mue.printStackTrace();
	         return Constants.DEFAULT_AJAX_FAILURE;
	      } catch (IOException ioe) {
	         System.out.println("出错了! 发生IO异常.");
	         ioe.printStackTrace();
	         return Constants.DEFAULT_AJAX_FAILURE;
	      } finally {
	         try {
	        	if(bw!=null){
	        		bw.close();
	        	}
	            is.close();
	         } catch (IOException ioe) {
	        	 ioe.printStackTrace();
	         }
	      }
	      
	      return Constants.DEFAULT_AJAX_SUCCESS;
	}
	
	//更换模板后，是以前的portlet更新过来。 
	@RequestMapping(value = "uptemp/{id}")
	public @ResponseBody String uptemp(@PathVariable	String id) throws ServletException, IOException {
		channelManager.uptemp(id);
		return Constants.DEFAULT_AJAX_SUCCESS;	

	}
	
}
